<template>
  <radio-group class="block" style="width: 100%;" @change="onRadioChange" :name="name">

    <view class="cu-form-group">
      <view class="title"><text v-if="required" class="text-red">*</text>{{ title }}</view>
      <view class="flex">
        <view v-for="(opt, idx) in options">
          <label class="text-sm">{{ opt.label }}</label>
          <radio
              :disabled="disabled"
              :class="['radio',opt.color ? opt.color : 'blue',radio === opt.value ? 'checked' : '']"
              :key="idx"
              :checked="radio === opt.value"
              :value="opt.value"
              style="transform: scale(0.8)"
          >
          </radio>
        </view>

      </view>
    </view>

  </radio-group>
</template>

<script lang="ts" setup>
import {inject, nextTick, onMounted, ref, watch, watchEffect, watchPostEffect} from "vue";

interface CuRadioOpt {
  value: string
  label: string
  color?: string
}

interface CuRadioProps {
  title: string
  name?: string
  options: CuRadioOpt[]
  disabled?: boolean
  required?: boolean
}

const props = withDefaults(defineProps<CuRadioProps>(), {
  disabled: false,
  required: false
})

const emit = defineEmits<{
  (e: 'change', value: string): void
}>()

const fields = inject<any>('fields')

const radio = ref('')

watchEffect(() => {
  if (props.name){
    if (props.options.length > 0){
      const value = fields[props.name]
      radio.value = String(value)
    }
  }
})

// watch(() => radio.value,(value) => {
//   if (props.name){
//     radio.value = value
//   }
// })


function onRadioChange(ev: any) {
  // radio.value = ev.detail.value
  if (props.name){
    fields[props.name] = ev.detail.value
  }
  emit('change', ev.detail.value)
}

</script>

<style scoped lang="scss">

</style>
